package com.sikulifang.bank.simulation.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;

import static com.sikulifang.bank.simulation.constant.TableConstants.RECEIPT_TABLE_NAME;

/**
 * ClassName FIleController
 * Description FIleController
 *
 * @author Yat
 * Date 2023年6月10日, 0010 16:32
 * version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    private Db db;

    @Lazy
    @Resource
    public void setDb(Db db) {
        this.db = db;
    }

    /**
     * Description: 文件下载
     * <p>
     *
     * @param receiptNumber 回单编号
     * @since 2023/4/11 16:20
     */
    @RequestMapping(value = "/download", method = {RequestMethod.GET, RequestMethod.POST})
    public void downloadExcelFile(@RequestParam String receiptNumber, HttpServletResponse response) {
        try {
            Entity entity = Entity.create(RECEIPT_TABLE_NAME);
            entity.set("receipt_number", receiptNumber);

            Entity fileEntity = db.get(entity);

            InputStream inputStream = FileUtil.getInputStream(fileEntity.getStr("content"));
            outputFile(inputStream, response.getOutputStream());

        } catch (SQLException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Description: 文件下载
     * <p>
     *
     * @since 2023/4/10 14:42
     */
    private void outputFile(InputStream inputStream, OutputStream out) {
        try (
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out)
        ) {
            StreamUtils.copy(bufferedInputStream, bufferedOutputStream);
        } catch (IOException | IORuntimeException e) {
            throw new RuntimeException("文件下载失败！platform：", e);
        }
    }
}
